﻿using Newtonsoft.Json;
using PMIS.Common;
using PMIS.Controls;
using PMIS.Dialogs;
using PMIS.Events;
using PMIS.HttpRequest;
using PMIS.Shared.DTO;
using PMIS.Shared.Models;
using PMIS.TemplatePrint.User;
using PMIS.Views;
using PMIS.Views.User;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;

namespace PMIS.ViewModels.User
{
    public class UserViewModel : ViewModelBase
    {
        private readonly IDialogService _dialogService;
        private readonly HttpService _httpService;
        private readonly IEventAggregator _eventAggregator;

        public UserViewModel(IDialogService dialogService, IEventAggregator eventAggregator, HttpService httpService)
        {
            _dialogService = dialogService;
            _httpService = httpService;
            _eventAggregator = eventAggregator;
            UserList = new ObservableCollection<UserDto>();

            LoadUserList(true);
        }

        private void StartLoading()
        {
            _eventAggregator.GetEvent<LoadingEvent>().Publish(new LoadingPayload() { IsLoading = true });
        }

        private void StopLoading()
        {
            _eventAggregator.GetEvent<LoadingEvent>().Publish(new LoadingPayload() { IsLoading = false });
        }

        private async void LoadUserList(bool loading = false)
        {
            if (loading)
            {
                StartLoading();
            }

            var parameters = new Dictionary<string, object>();
            if (!string.IsNullOrEmpty(this.SearchName))
            {
                parameters["name"] = this.SearchName;
            }
            if (_searchGender >= 0)
            {
                parameters["gender"] = _searchGender;
            }
            var response = await _httpService.GetAsync(Api.USER_GET_LIST, parameters);
            if (response?.code == 1)
            {
                var data = JsonConvert.DeserializeObject<PagingModel<UserDto>>(JsonConvert.SerializeObject(response.data));
                var items = data.Items;
                UserList = new ObservableCollection<UserDto>(items);
            }

            StopLoading();
        }

        private int? _searchGender;

        public int? SearchGender
        {
            get
            {
                return _searchGender;
            }
            set
            {
                SetProperty(ref _searchGender, value);
            }
        }

        private string _searchName;

        public string SearchName
        {
            get { return _searchName; }
            set { SetProperty(ref _searchName, value); }
        }

        private ObservableCollection<UserDto>? _userList;
        public ObservableCollection<UserDto>? UserList
        {
            get
            {
                return _userList;
            }
            set
            {
                SetProperty(ref _userList, value);
            }
        }

        private void OnAdd()
        {
            _dialogService.ShowDialog(nameof(AddEditUser), null, AddEditCallBack);
        }

        private async void OnDelete()
        {
            var count = UserList.Count(p => p.IsChecked == true);
            if (count == 0)
            {
                ToastManager.ShowToast("请选择要删除的数据");
                return;
            }
            var dialogResult = System.Windows.MessageBox.Show("是否删除选择的数据", "提示", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (dialogResult == MessageBoxResult.Yes)
            {
                List<string?> ids = UserList.Where(p => p.IsChecked == true).Select(p => p.Id).ToList();
                await DeleteUserList(ids);
                ids.ForEach((id) =>
                {
                    var r = UserList.First(p => p.Id == id);
                    UserList.Remove(r);
                });
            }
        }

        private async Task<bool> DeleteUserList(List<string?> ids)
        {
            var response = await _httpService.PostAsync(Api.USER_DELETE, ids);
            if (response?.code == 1)
            {
                return true;
            }
            return false;
        }

        private void OnEdit(object obj)
        {
            if (obj is UserDto user)
            {
                DialogParameters para = new DialogParameters();
                para.Add("data", user.DeepClone());
                _dialogService.ShowDialog(nameof(AddEditUser), para, AddEditCallBack);
            }
        }

        private void OnPrint()
        {
            UserDocumentRenderer render = new UserDocumentRenderer();
            string strTmplName = $"/PMIS;component/TemplatePrint/User/UserTemplate.xaml";
            PrintPreviewWindow window = new PrintPreviewWindow(strTmplName, this.UserList, render);
            window.ShowDialog();
        }

        private void OnRefresh()
        {
            this.LoadUserList(true);
        }

        private void OnSearch()
        {
            this.LoadUserList(true);
        }

        private ICommand _searchCommand;
        public ICommand SearchCommand => _searchCommand ??= new DelegateCommand(OnSearch);

        private ICommand _addCommand;
        public ICommand AddCommand => _addCommand ??= new DelegateCommand(OnAdd);

        private ICommand _editCommand;
        public ICommand EditCommand => _editCommand ??= new DelegateCommand<object>(obj => OnEdit(obj));

        private ICommand _deleteCommand;
        public ICommand DeleteCommand => _deleteCommand ??= new DelegateCommand(OnDelete);

        private ICommand _printCommand;
        public ICommand PrintCommand => _printCommand ??= new DelegateCommand(OnPrint);

        private ICommand _refreshCommand;
        public ICommand RefreshCommand => _refreshCommand ??= new DelegateCommand(OnRefresh);

        private void AddEditCallBack(IDialogResult dialogResult)
        {
            if (dialogResult != null && dialogResult.Result == ButtonResult.OK)
            {
                LoadUserList();
            }
        }
    }
}
